<html>
<head>
<title>CS143 Project 1b
</title>
</head>
<body>
<p>
Please make sure the MySQL command you type in is correct:
</p>
<form action="query.php" method="GET">
<textarea name="query" cols="60" rows="8"></textarea>
<input type="submit" value="Submit" />

</form>
<p>Note: tables and fields are case sensitive. Run "show tables" to see the list of
available tables.
</p>

<h3>Result:</h3>
<?php
function dumpquery($query) {
    $numfields = mysql_num_fields($query);
    echo '<table border="1" cellpadding="0" cellspacing="0"<tr>';
    for ($i = 0; $i<$numfields; $i += 1) {
         $field = mysql_fetch_field($query, $i);
         echo '<th>' . $field->name . '</th>';
    }
    echo '</tr>';
    while ($fielddata = mysql_fetch_array($query)) {
        echo '<tr>';
        for ($i = 0; $i<$numfields; $i += 1) {
             $field = mysql_fetch_field($query, $i);
            echo '<td>' . $fielddata[$field->name] . '</td>';
        }
        echo '</tr>';
    }
    echo '</table>';    
}
 
if($query = $_GET["query"]) {
	// connect to mysql
	$link = mysql_connect('localhost', 'cs143', '');
	if (!$link) {
		die('Could not connect: ' . mysql_error());
	}
	// select a database
	$db_selected = mysql_select_db('CS143', $link);
	if (!$db_selected) {
		die ('Can\'t use database : ' . mysql_error());
	}
	// send a query
	$result = mysql_query($query);
	if (!$result) {
		die('Invalid query: '. mysql_error());
	}
	dumpquery($result);
	mysql_close($link);
}
?>
</body>
</html>
